/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-16 Time: 17:25
 *
 * 新建报修工单 => 上传图片
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    View,
    TouchableOpacity,
    Text,
    Modal,
    ScrollView, Image,
    Dimensions,
    ToastAndroid, TouchableHighlight,
} from 'react-native';

import {connect} from 'react-redux';
import ActionSheet from 'react-native-actionsheet'
import ImageViewer from 'react-native-image-zoom-viewer'
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../../../../constant/PHScreen"
import {COLOR_GRAY_LINE} from "../../../../constant/PHColors"
import AntDesign from "react-native-vector-icons/AntDesign"
import BottomButtonView from "../../../../component/BottomButtonView/BottomButtonView"
import ImagePicker from "react-native-image-crop-picker"
import {getStore} from "../../../../configuration/StoreConfiguration";
import global from "../../../../configuration/global";
import {AppRequestPath} from "../../../../configuration/AppConfig";
import {API_UPLOADIMG} from "../../../../constant/API";
import User from "../../../../model/User/User";

class RepairWorkOrderUploadImageBase64Screen extends Component {

    static navigationOptions = {
        title: '选择图片'
    }

    //构造
    constructor(props) {
        super(props);

        let {imageArr} = this.props.navigation.state.params;
        this.state = {
            clickNum:0,
            showBigPicIndex:1,
            imageArr:imageArr||[{},{},{},{},{},{},{},{},{}], //图片数组
            showBigPicModal:false,//查看大图modal
            showBigPicUrlArr:[],//查看大图url
        }
    }

    render() {
        return (
            <SafeAreaView style={{flex: 1}}>

                <ScrollView style={{flex: 1}}>

                    <View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
                        {
                            this.state.imageArr.map((item, index) => {
                                return this._renderItem(item, index)
                            })
                        }
                    </View>

                </ScrollView>

                <BottomButtonView title={'完成'} onSubmitClick={() => {

                    let imageArr=this.state.imageArr;
                    let outArr = [{},{},{},{},{},{},{},{},{}]
                    for (let i = 0; i < imageArr.length; i++) {
                        if(imageArr[i]['base64']){
                            outArr[i]['base64'] = imageArr[i]['base64']
                        }
                    }
                    this.props.navigation.state.params.goBack(outArr);
                }}/>

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'选择图片'}
                    options={['查看','相册', '拍照', '取消']}
                    cancelButtonIndex={3}
                    onPress={(index) => {
                        switch (index) {
                            case 0: {
                                // console.log(JSON.stringify(this.state.imageArr))
                                let index = this.state.clickNum;
                                // this.state.showBigPicUrl = this.state.imageArr[index]['path'];

                                let showBigPicUrlArr = []

                                let showBigPicIndex = 0
                                for (let i = 0; i < this.state.imageArr.length; i++){
                                    let showBigPicUrl = {}
                                    if(this.state.imageArr[i]['base64']){
                                        if(this.state.imageArr[i]['localImg']){
                                            // showBigPicUrl = {url:this.state.imageArr[i]['path']}
                                            showBigPicUrl = {url:'data:image/png;base64,'+this.state.imageArr[i]['base64']}
                                        }else{
                                            // showBigPicUrl = {url:AppRequestPath()+"/img/"+global.hotelId+"/"+this.state.imageArr[i]['path']}
                                            showBigPicUrl = {url:'data:image/png;base64,'+this.state.imageArr[i]['base64']}

                                        }
                                        showBigPicUrlArr.push(showBigPicUrl)
                                        if(this.state.imageArr[i]['base64']===this.state.imageArr[index]['base64']){
                                            showBigPicIndex = showBigPicUrlArr.length-1
                                        }
                                    }
                                }

                                if(this.state.imageArr[index]['base64']){
                                    this.setState({
                                        showBigPicIndex:showBigPicIndex,
                                        showBigPicUrlArr:showBigPicUrlArr,
                                        showBigPicModal:true
                                    })
                                }else{
                                    ToastAndroid.show('请先添加图片！', 1000);
                                }


                                break;
                            }
                            case 1: {
                                ImagePicker.openPicker({
                                    multiple: true,
                                    includeBase64: true,
                                }).then(images => {
                                    console.log(images,this.state.clickNum);

                                    let arr = this.state.imageArr;
                                    let outjson = {"localImg":1,"base64":images[0].data};
                                    arr[this.state.clickNum] = outjson;
                                    this.setState({
                                        imageArr : arr,
                                    })


                                });

                                break;
                            }
                            case 2: {
                                ImagePicker.openCamera({
                                    width: 400,
                                    height: 300,
                                    cropping: true,
                                    includeBase64: true,
                                }).then(image => {
                                    // let arr = this.state.imageArr;
                                    // image.localImg=1;
                                    // arr[this.state.clickNum] = image;
                                    // this.setState({
                                    //     imageArr : arr,
                                    // })

                                    //图片转base64
                                    // let Buffer = require('buffer').Buffer;
                                    // let base64Str= new Buffer(image.data).toString('base64');

                                    let arr = this.state.imageArr;
                                    let outjson = {"localImg":1,"base64":image.data};
                                    arr[this.state.clickNum] = outjson;
                                    this.setState({
                                        imageArr : arr,
                                    })

                                });
                                break;
                            }
                            default: {
                                break;
                            }
                        }
                    }}
                />

                {/*查看大图*/}
                <Modal
                    visible={this.state.showBigPicModal}
                    //显示是的动画默认none
                    //从下面向上滑动slide
                    //慢慢显示fade
                    animationType = {'slide'}
                    //是否透明默认是不透明 false
                    transparent = {true}
                    //关闭时调用
                    // onRequestClose={()=> this.onRequestClose()}
                >
                    <View style={{flex: 1, backgroundColor: '#000'}} >
                        <View style={{alignItems:'center',justifyContent:'center',flexDirection:'column',width:SCREEN_WIDTH,height:SCREEN_HEIGHT}} >
                            {/*<Image source={{uri:this.state.showBigPicUrl}}  style={{width: SCREEN_WIDTH , height:SCREEN_WIDTH-20,}} />*/}

                            <ImageViewer
                                imageUrls={this.state.showBigPicUrlArr} // 照片路径
                                index={this.state.showBigPicIndex}
                                enableImageZoom={true} // 是否开启手势缩放
                                style={{width: SCREEN_WIDTH, height: SCREEN_WIDTH-20}}
                                enableSwipeDown={false}
                                onChange={(index) => { }} // 图片切换时触发
                                onClick={() => { // 图片单击事件
                                    this.onRequestClose()
                                }}
                            />
                        </View>
                    </View>
                </Modal>

            </SafeAreaView>
        )
    }


    onRequestClose(){
        this.setState({
            showBigPicModal: false,
        })
    }

    _renderItem(item, index) {
        return (
            <View key={index} style={{width: SCREEN_WIDTH / 3, height: SCREEN_WIDTH / 3, justifyContent: 'center', alignItems: 'center'}}>
                <TouchableOpacity key={index} activeOpacity={0.8} onPress={() => {
                    this.state.clickNum = index;
                    this.ActionSheet.show();
                }}>
                    {/*{
                this.state.imageArr[index]['path'] ? (
                    <Image source={{uri:this.state.imageArr[index]['path']}}  style={{width: SCREEN_WIDTH / 3 - 30, height: SCREEN_WIDTH / 3 - 30,}} />
                ) : (
                    <View
                        key={index}
                        style={{
                            margin: 15,
                            width: SCREEN_WIDTH / 3 - 30,
                            height: SCREEN_WIDTH / 3 - 30,
                            borderRadius: 10,
                            borderColor: COLOR_GRAY_LINE,
                            borderWidth: 1,
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                        <AntDesign name={'plus'} size={40} style={{color: COLOR_GRAY_LINE}}/>
                    </View>
                )
            }*/}
                    <View
                        key={index}
                        style={{
                            margin: 15,
                            width: SCREEN_WIDTH / 3 - 30,
                            height: SCREEN_WIDTH / 3 - 30,
                            borderRadius: 10,
                            borderColor: COLOR_GRAY_LINE,
                            borderWidth: 1,
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                        {
                            this.state.imageArr[index]['base64'] ? (
                                (this.state.imageArr[index]['localImg'] ?
                                        <Image source={{uri:'data:image/png;base64,'+this.state.imageArr[index]['base64']}}  style={{width: SCREEN_WIDTH / 3 - 30, height: SCREEN_WIDTH / 3 - 30}} />:
                                        <Image source={{uri:'data:image/png;base64,'+this.state.imageArr[index]['base64']}}  style={{width: SCREEN_WIDTH / 3 - 30, height: SCREEN_WIDTH / 3 - 30}} />
                                )) : (
                                <AntDesign name={'plus'} size={40} style={{color: COLOR_GRAY_LINE}}/>
                            )
                        }
                    </View>


                </TouchableOpacity>

                <View style={{position: 'absolute', width: 20, height: 20}}>

                </View>
            </View>
        )
    }

    _onSubmitClick() {

    }

    _showActionSheet = () => {
        this.ActionSheet.show()
    }

}

const props = state => {
    return {}
}

export default RepairWorkOrderUploadImageBase64Screen = connect(props)(RepairWorkOrderUploadImageBase64Screen);

const styles = StyleSheet.create({})